﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AbstraX;
using AbstraX.Contracts;
using SolutionFramework.Entities;
using Microsoft.Practices.Unity;
using MvvmTreeView;
using System.Windows.Threading;
using AbstraX.ClientInterfaces;
using DataBindings.Services;
using System.Reflection;
using AbstraX.BuildWizard;
using Mvvm;
using AbstraX.BindingsTreeEntities;
using System.Threading;
using System.Diagnostics;

namespace DataBindings
{
    public partial class BindingsControl : UserControl, IWizardFrame
    {
        public string URL { get; set; }
        public Assembly Assembly { get; set; }
        private string parms;
        private BindingsTreeService service;
        private IWizardContainer container;
        private bool nextEnabled;

        public BindingsControl()
        {
            ProviderLoader.Initialize();

            InitializeComponent();
        }

        public IWizardContainer WizardContainer
        {
            set 
            {
                container = value;
            }
        }

        public string Parms
        {
            get
            {
                return parms;
            }
            set
            {
                parms = value;

                var container = ProviderLoader.Container;

                service = new BindingsTreeService(this.Parms);

                container.RegisterInstance<IBindingsTreeService>(service);
            }
        }

        private void Load()
        {
            var container = ProviderLoader.Container;
            var viewModel = container.Resolve<IBindingsViewModel>();
            var context = new SolutionFrameworkDomainContext();
            var messageQueue = new Queue<string>();
            var waiting = false;

            ProviderLoader.StatusLabel = this.StatusBar;
            ProviderLoader.SetStatus("Initializing...");

            viewModel.TreeView.InternalTreeView = BindingsTreeView.InternalTreeView;
            viewModel.TreeView.Busy += new MvvmTreeView.BusyHandler(TreeView_Busy);
            viewModel.TreeView.OnStatus += new StatusHandler(TreeView_OnStatus);
            
            viewModel.TreeView.RootNodesAvailable += (treeView, rootNodes) =>
            {
                ProviderLoader.SetStatus("Ready.");
                nextEnabled = true;

                this.container.EnableNext();
            };

            BindingsTreeView.DataContext = viewModel;
            BindingsTreeView.Focus();

            var timer = new DispatcherTimer();

            timer.Tick += (sender2, e2) =>
            {
                if (!waiting) // Monitor.TryEnter not working
                {
                    waiting = true;

                    try
                    {

                        var operation = context.GetStatusMessages();

                        operation.Completed += (sender3, e3) =>
                        {
                            try
                            {
                                var messages = operation.Value;

                                if (messages != null)
                                {
                                    messages.ToList().ForEach(m => messageQueue.Enqueue(m));
                                }
                            }
                            catch (Exception ex)
                            {
                                messageQueue.Enqueue(ex.Message);
                            }

                            waiting = false;
                        };
                    }
                    catch (Exception ex)
                    {
                        messageQueue.Enqueue(ex.Message);
                    }
                }

                if (messageQueue.Count > 0)
                {
                    ProviderLoader.SetStatus(messageQueue.Dequeue());
                }
            };

            timer.Interval = new TimeSpan(0, 0, 0, 0, 1000); // one second
            timer.Start();
        }

        private void TreeView_OnStatus(ITreeNode treeNode, string status)
        {
            if (status != null && status.Length > 0)
            {
                ProviderLoader.SetStatus("Data Type: " + status);
            }
            else
            {
                ProviderLoader.SetStatus(status);
            }
        }

        private void TreeView_Busy(ITreeNode treeNode, bool busy)
        {
            if (busy)
            {
                ProviderLoader.SetStatus(treeNode.Text + " loading...");
            }
            else
            {
                ProviderLoader.SetStatus("");
            }
        }

        public UserControl FrameControl
        {
            get 
            {
                return this;
            }
        }

        public ICommand ShowFrameCommand
        {
            get
            {
                return new MvvmCommand(e =>
                {
                    Load();
                }, null);
            }
        }

        public ICommand NextPageCommand
        {
            get
            {
                return new MvvmCommand(e =>
                {
                    string treeIDs = null;

                    service.BindingsTrees.Cast<BindingsTreeEntity>().ToList().ForEach(b => treeIDs += b.ID + ",");

                    if (treeIDs.Length > 0)
                    {
                        treeIDs = treeIDs.Remove(treeIDs.Length - 1);

                        var buildInvoke = container.SetProperty(this.URL, "TreeIDs", treeIDs);

                        buildInvoke.OnBuildCompleted += (sender, e2) =>
                        {
                            service.Refresh();
                            container.MoveNext(this.URL);
                        };
                    }
                    else
                    {
                        Debugger.Break();
                    }

                }, null);
            }
        }

        public ICommand PreviousPageCommand
        {
            get
            {
                return new MvvmCommand(e =>
                {
                    service.Refresh();

                }, null);
            }
        }

        public ICommand CancelCommand
        {
            get 
            {
                return new MvvmCommand(e =>
                {

                }, null);
            }
        }

        public ICommand FinishCommand
        {
            get 
            {
                return new MvvmCommand(e =>
                {

                }, null);
            }
        }

        public string Caption
        {
            get 
            {
                return "Data Bindings";
            }
        }

        public string Description
        {
            get 
            {
                return "Data Bindings Description";
            }
        }

        public bool NextEnabled
        {
            get 
            {
                return nextEnabled;
            }
        }

        public bool FinishEnabled
        {
            get 
            {
                return false;
            }
        }
    }
}
